﻿using System;
using System.Collections;
using System.Drawing;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;
using KPIS.GERP.GBMS.APP_UI.UserControls;
using KPIS.GERP.GBMS.APP_UI.Common;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Project_Expense_Change : System.Web.UI.Page
    {
        private ComboBLL comboBLL = new ComboBLL();
        private IProject projectBLL = new Project_BLL();
        private ISourceBLL src = new SourceBLL();
        private IExpenseGroupBLL expGrp = new ExpenseGroupBLL();
        private Expense_BLL exp = new Expense_BLL();
        Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lbProjectID.Text = Request.QueryString["hid"];
                //litTitle.Text = Request.QueryString["hname"];

                LoadSource();
                LoadExpenseGroup();
                LoadData();
            }
        }

        private void LoadData()
        {
            string strProjectSeq = lbProjectID.Text;
            string strSourceSeq = cbSource.SelectedValue;
            string strExpGrpSeq = cbExpenseGroup.SelectedValue;
            DataTable dtb = projectBLL.GetDataProjectBySequence(strProjectSeq);

            if (!cbExpenseGroup.Visible)
            {
                strExpGrpSeq = "";
            }

            litTitle.Text = dtb.Rows[0]["bgm_prj_name"].ToString();
            dtb = projectBLL.GetDataProjectExpenseOnlyExp(strProjectSeq, strSourceSeq, strExpGrpSeq);
            gridExpense.DataSource = dtb;
            gridExpense.DataBind();

            SumOldTotalAmount(dtb);
        }

        private void SumOldTotalAmount(DataTable dtb)
        {
            double dSumTotalAmount = 0;

            for (int i = 0; i < dtb.Rows.Count; i++)
            {
                dSumTotalAmount += Convert.ToDouble(dtb.Rows[i]["total_amount"]);
            }

            string strSumTotalAmount = dSumTotalAmount.ToString("#,###.##");

            if (strSumTotalAmount.Length == 0)
            {
                strSumTotalAmount = "0.00";
            }

            lbOldAmount.Text = strSumTotalAmount;
            lbNewAmount.Text = strSumTotalAmount;
        }

        private void SumNewTotalAmount()
        {
            double dSumTotalAmount = 0;

            for (int i = 0; i < gridExpense.Items.Count; i++)
            {
                GridDataItem item = gridExpense.Items[i];
                RadNumericTextBox txt = (RadNumericTextBox)item["total_amount"].FindControl("txtTotalAmount");
                dSumTotalAmount += (txt.Value != null ? txt.Value.Value : 0);
            }

            string strSumTotalAmount = dSumTotalAmount.ToString("#,###.##");

            if (strSumTotalAmount.Length == 0)
            {
                strSumTotalAmount = "0.00";
            }

            lbNewAmount.Text = strSumTotalAmount;
        }

        private void LoadSource()
        {
            cbSource.DataSource = comboBLL.ListSourceCombo();
            cbSource.DataBind();

            cbSource.SelectedIndex = 0;
        }

        private void LoadExpenseGroup()
        {
            cbExpenseGroup.DataSource = expGrp.Search(0, "", "", "", 0, 0);
            cbExpenseGroup.DataBind();

            cbExpenseGroup.SelectedIndex = 0;
        }

        private void LoadExpense()
        {
            string strBgmExpGrpSeq = cbExpenseGroup.SelectedValue;

            if (!cbExpenseGroup.Visible)
            {
                strBgmExpGrpSeq = "";
            }

            cbExpense.DataSource = exp.GetLeafExpense(strBgmExpGrpSeq);
            cbExpense.DataBind();

            cbExpense.SelectedIndex = 0;
            cbExpense_SelectedIndexChanged(null, null);
        }

        private void UpdateUI(string strMode)
        {
            bool bViewMode = (strMode == "View");

            pnButton.Visible = bViewMode;
            pnAddNew.Visible = !bViewMode;
            cbSource.Enabled = bViewMode;
            cbExpenseGroup.Enabled = bViewMode;
            gridExpense.Enabled = bViewMode;
            lbError.Visible = false;
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            UpdateUI("Add");
            LoadExpense();
        }

        protected void Insert_Click(object sender, EventArgs e)
        {
            string strBgmExpSeq = cbExpense.SelectedValue;
            string strBgmSourceSeq = cbSource.SelectedValue;
            string strBgmProjSeq = lbProjectID.Text;
            string strEmpSeq = new SsMng().GetUss(SsMng.SsUserType.EmpSeq);
            string strAmount = "0";
            int? ResItemSeq = null;
            int? Qty = null;
            decimal? Price = null;

            if (PanelInv.Visible)
            {
                ResItemSeq = main.ConvertNullInt(ddlResourceSubGroup.SelectedValue.Split('-')[0]);
                Qty = main.ConvertNullInt(txtUnitQty.Text);
                Price = main.ConvertNullDecimal(txtUnitPrice.Text);
                //strAmount = txtAmount.Text;
            }

            projectBLL.InsertProjectExpense(strBgmProjSeq, strBgmSourceSeq, strBgmExpSeq, strAmount//strTotalAmount
                , null, ResItemSeq, Qty, Price, null, null, null, strEmpSeq);
            UpdateUI("View");
            LoadData();
        }

        protected void Update_Click(object sender, EventArgs e)
        {
            lbError.Visible = false;
            lbError2.Visible = false;
            string strEmpSeq = new SsMng().GetUss(SsMng.SsUserType.EmpSeq);
            double dOldSumTotalAmount = Convert.ToDouble(lbOldAmount.Text);
            double dNewSumTotalAmount = Convert.ToDouble(lbNewAmount.Text);

            if (dOldSumTotalAmount != dNewSumTotalAmount)
            {
                lbError.Visible = true;
                return;
            }

            for (int i = 0; i < gridExpense.Items.Count; i++)
            {
                GridDataItem item = gridExpense.Items[i];
                string strBgmProjExpSeq = item["bgm_proj_exp_seq"].Text;
                Nullable<double> dOldTotalAmount = Convert.ToDouble(((Label)item["total_amount"].FindControl("lbTotalAmount")).Text);
                Nullable<double> dNewTotalAmount = ((RadNumericTextBox)item["total_amount"].FindControl("txtTotalAmount")).Value;
                //if (dNewTotalAmount < 0)
                //{
                //    lbError2.Visible = true;
                //    return;

                //}
                if (dOldTotalAmount != dNewTotalAmount)
                {
                    string strUsedAmount = (dNewTotalAmount == null ? "0" : dNewTotalAmount.Value.ToString());
                    string strCalAmount = (dNewTotalAmount == null ? (- dOldTotalAmount.Value).ToString() : (dNewTotalAmount.Value - dOldTotalAmount.Value).ToString());
                    string strRtpType = (Convert.ToDouble(strCalAmount) > 0 ? "3" : "2");

                    projectBLL.UpdateTotalAmountProjectExpense(strBgmProjExpSeq, "เป็นแปลงวงเงินค่าใช้จ่าย", strUsedAmount, strCalAmount, strRtpType, strEmpSeq);
                }
            }

            UpdateUI("View");
            LoadData();
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            UpdateUI("View");
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            string strBgmProjExpSeq = gridExpense.SelectedValue.ToString();

            if (strBgmProjExpSeq == null || strBgmProjExpSeq == "")
            {
                return;
            }

            projectBLL.DeleteProjectExpense(strBgmProjExpSeq);
            LoadData();
        }

        protected void cbSource_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strSourceSeq = cbSource.SelectedValue;

            if (strSourceSeq == "6" || strSourceSeq == "7")
            {
                cbExpenseGroup.Visible = false;
                lblException.Visible = true;
            }
            else
            {
                cbExpenseGroup.Visible = true;
                lblException.Visible = false;
            }

            LoadData();
        }

        protected void cbExpenseGroup_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadData();
        }

        protected void txtTotalAmount_TextChanged(object sender, EventArgs e)
        {
            SumNewTotalAmount();
        }

        protected void gridExpense_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            string strProjectSeq = lbProjectID.Text;
            string strSourceSeq = cbSource.SelectedValue;
            string strExpGrpSeq = cbExpenseGroup.SelectedValue;
            DataTable dtb = projectBLL.GetDataProjectExpenseOnlyExp(strProjectSeq, strSourceSeq, strExpGrpSeq);

            gridExpense.DataSource = dtb;
            SumOldTotalAmount(dtb);
        }

        protected void LoadDdlResourceSubGroup()
        {
            Nullable<int> nBgmExpSeq = main.ConvertNullInt(cbExpense.SelectedValue);
            ddlResourceSubGroup.DataSource = comboBLL.ListResourceDDL(nBgmExpSeq);
            ddlResourceSubGroup.DataBind();
        }

        private void SetTotalAmount()
        {
            double dUnitQty = (double.TryParse(txtUnitQty.Text, out dUnitQty) ? dUnitQty : 0);
            double dUnitPrice = (double.TryParse(txtUnitPrice.Text, out dUnitPrice) ? dUnitPrice : 0);

            txtAmount.Text = (dUnitQty * dUnitPrice).ToString("#,##0.00");
        }

        protected void txtUnitQty_TextChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }

        protected void txtUnitPrice_TextChanged(object sender, EventArgs e)
        {
            SetTotalAmount();
        }

        protected void cbExpense_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(cbExpense.SelectedValue))
            {
                DataTable dtb = exp.GetInfo(cbExpense.SelectedValue);

                if (dtb.Rows.Count > 0)
                {
                    if (dtb.Rows[0]["bgm_exp_grp_id_real"].ToString() == "3")
                    {
                        PanelInv.Visible = true;
                        LoadDdlResourceSubGroup();
                    }
                    else
                    {
                        PanelInv.Visible = false;
                    }
                }
            }
        }
    }
}
